import { decryptData } from './crypto'
import { getBaseUrlBlog } from '~/api/request'

// 获取 cookie
export const getCookie = (name: string): string | null => {
  const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'))
  // 需要解密一下token
  return match ? decryptData(match[2]) : null
}

// 设置 cookie
export const setCookie = (name: string, value: string, days: number) => {
  const expires = new Date()
  expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000)
  document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/`
}

// 清除 cookie
export const clearCookie = (name: string) => {
  setCookie(name, '', -1)
}

// 判断是否登录
export const hasLogin = (): boolean => {
  return !!getCookie('blog_t_enc')
}

// 退出登录
export const logout = () => {
  clearCookie('blog_t_enc')
  localStorage.removeItem('u_info_enc')
  window.location.href = getBaseUrlBlog() // 修改为返回首页
}
